<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form"  @submit.native.prevent>
      <div class="form-title">
        <img :src="imgLogo" alt />
      </div>
      <el-form-item prop="username" v-if="keyAccInit && this.loginType!='1'">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="请输入用户名">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="请输入密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaOnOff">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="请输入验证码"
          style="width: 60%"
          @keyup.enter.native="handleLogin"
        >
          <template slot="prefix">
            <img src="../assets/images/Code@3x.png" alt class="code_img" />
          </template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>
      <!--      <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px">记住密码
      </el-checkbox>-->
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="big"
          type="primary"
          style="width: 100%; background-color: #4295eb"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
      <div style="width: 100%; font-size: 14px; text-align: center; line-height: 20px">
        <span style="color: red">{{ errMsg }}</span>
      </div>
      <div style="width: 100%;font-size:14px;text-align: center;line-height: 20px;" v-if="keySwitch==1 && loginType!=='2'">
        <el-link :underline="false" href="/hkkeywspulgin" icon="el-icon-download" style="color:#ffffff" target="_blank" >下载KEY驱动</el-link>
      </div>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>建议分辨率最佳分辨率1920*1080</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from '@/api/login'
import { addlockKey, getLockKey, queryKeyConfig,initConfig } from '@/api/system/sysUkey'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { mapState, mapActions } from 'vuex'
import { MessageBox } from 'element-ui'
export default {
  name: 'Login',
  data() {
    return {
      codeUrl: '',
      imgLogo: '',
      loginForm: {
        username: '',
        password: '',
        pinLogin:false,
        rememberMe: false,
        code: '',
        uuid: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
        password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
        code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
      },
      loading: false,
      // 验证码开关
      captchaOnOff: false,
      // 注册开关
      register: false,
      redirect: undefined,
      errMsg: '',
      //登录方式，0、key或账号密码 1、必须使用key 2、账号密码
      loginType:0,
      //系统是否使用key授权或登录
      keySwitch:0,
      //授权点数是否已初始化 0、否 1、是
      keyEmpower:0,
      //发货标识
      sendProduct:'',
      //检测key号
      keySn:'',
      setIntervalKey:null,
      lockKey:false,
      initLockKey:false,
      //是否查询试用期
      tryTime:'',
      tryTimeInit:true,
      tryTimeget:false,
      //key使用的账号
      keyAcc:'',
      keyAccInit:true,
      //key绑定的发货id
      keySendProduct:'',
      keyTryTime:'',
      //初始化数据
      initData: null
      // initData:{
      //   //初始化json
      //   initJson: "",
      //   //授权类型
      //   tallyMethod: "",
      //   //绑定服务器的mac地址
      //   macList:""
      // }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    // this.getCode();
    this.getCookie()
    this.setImgLogo()
  },
  created() {
    //获取key配置
    this.KeyConfig()
  },
  beforeDestroy() {
    window.removeEventListener('onmessageWS', this.getSocketData)
  },
  computed: {
    ...mapState({
      logoImg: state => state.app.logoImg
    })
  },
  methods: {
    // 获取logo图片的方法
    ...mapActions({
      getLogoImg: 'app/getLogoImg'
    }),
    setImgLogo() {
      this.getLogoImg().then(res => {
        this.imgLogo = res?.imagePath + res?.blue?.loginImg
      })
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff
        if (this.captchaOnOff) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.loginForm.uuid = res.uuid
        }
      })
    },
    getCookie() {
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      // const rememberMe = Cookies.get('rememberMe')
      const roleName = JSON.parse(sessionStorage.userInfo || '{}').roleName
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        roleName: roleName === undefined ? this.loginForm.roleName : roleName,
        password: password === undefined ? this.loginForm.password : decrypt(password)
        // rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      }
    },
    handleLogin() {
      //试用期
      if(this.tryTimeget){
        this.$message.warning("已过试用期")
        return
      }
      if(this.keySn && !this.keyAccInit && (this.sendProduct && this.sendProduct != this.keySendProduct)){
        this.$message.warning("当前key无法登录该系统")
        return
      }

      if(!this.lockKey){
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            if(this.loginType=="0"){
              if(this.keySn && !this.keyAccInit){
                //验证key使用账号
                if(!this.keyAcc){
                  this.$message.warning("未查询到KEY关联的账号信息，请稍后重试")
                  return
                }
                //验证key的pin
                this.keyVerifyPin(this.loginForm.password)
              }else{
                this.sendLogin();
              }
            }else if(this.loginType=="1"){
              if(this.keySn){
                //验证key使用账号
                if(!this.keyAcc){
                  this.$message.warning("未查询到KEY关联的账号信息，请稍后重试")
                  return
                }
                //验证key的pin
                this.keyVerifyPin(this.loginForm.password)
              }else{
                this.$message.warning("请确认下载KEY驱动并已经插入KEY")
              }
            }else{
              this.sendLogin();
            }
          }
        })
      }
    },
    sendLogin(){
      this.loading = true
      if (this.loginForm.rememberMe) {
        Cookies.set('username', this.loginForm.username, { expires: 30 })
        Cookies.set('roleName', this.loginForm.roleName, { expires: 30 })
        Cookies.set('password', encrypt(this.loginForm.password), {
          expires: 30
        })
        Cookies.set('rememberMe', this.loginForm.rememberMe, {
          expires: 30
        })
      } else {
        Cookies.remove('username')
        Cookies.remove('password')
        Cookies.remove('roleName')
        Cookies.remove('rememberMe')
      }
      this.loginForm.password = encrypt(this.loginForm.password);
      this.$store
        .dispatch('Login', this.loginForm)
        .then(() => {
          //key登录缓存
          Cookies.set('keySn', this.keySn)
          Cookies.set('loginType', this.loginType)
          if(this.loginForm.pinLogin==true){
            Cookies.set('pinLogin', true)
          }else{
            Cookies.set('pinLogin', false)
          }

          this.$router.push({ path: this.redirect || '/' }).catch(() => {
          })
        })
        .catch((e) => {
          this.loading = false
          this.loginForm.password = ''
          this.loginForm.code = ''
          this.errMsg = e
          if (this.captchaOnOff) {
            this.getCode();
          }
        })
    },
    KeyConfig(){
      queryKeyConfig().then(res => {
        this.loginType = res.loginType
        this.keyEmpower = res.keyEmpower
        this.sendProduct = res.sendProduct
        this.keySwitch = res.keySwitch
        if(this.keySwitch==1){
          // 注册监听事件
          window.addEventListener('onmessageWS', this.getSocketData)
        }
        //验证是否超过有效期
        if(res.tallyValidity){
          this.tryTime = res.tallyValidity
          this.errMsg = "试用期截止到："+res.tallyValidity
          this.tryTimeget =res.tryTimeget
        }

        // //登录类型
        // if(res.loginType=="1"){
        //   this.keyAccInit=false
        // }
        if(this.keyEmpower==0 && this.keySwitch==1){
          this.initTally()
        }
      })
    },
    //初始化授权
    initTally(){
      this.$msgbox.confirm(
        '当前系统授权数据未初始化操作，请先初始化操作',
        '系统提示', {
          confirmButtonText: '初始化',
          cancelButtonText: "关闭",
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              if (!this.keySn) {
                this.$message.warning("请确认下载KEY驱动并已经插入KEY")
              }else{
                if(!this.initData || (this.initData.tallyMethod && !this.initData.tallyMethod.split(',').includes(window.tallyMethod))){
                  this.$message.warning("KEY无初始化权限")
                // }else if(!this.initData.initJson){
                //   this.$message.warning("未获取到授权数据，请刷新重试或换KEY重试")
                }else{
                  instance.confirmButtonLoading = true
                  instance.confirmButtonText = '初始化中...'
                  if(!this.keySendProduct){
                    instance.confirmButtonLoading = false
                    instance.confirmButtonText = '初始化'
                    this.$message.warning("当前key未绑定发货信息,无法初始化")
                  }else{
                    // alert(123)
                    this.initSysConfig()
                  }
                }
              }
            } else {
              MessageBox.close()
            }
          }
        }
      )

    },
    //framwork初始化
    initSysConfig(){
      initConfig(this.keySendProduct,this.keyTryTime).then(res => {
        if(res){
          //成功，获取mac地址、重写Key配置文件
          this.initData.macList = res.join(",")
          let cmdData = {
            "key_sn": this.keySn,
            "file_name": window.keyAuthorizedPointsFileName,
            "write_data": JSON.stringify(this.initData),
          }
          this.$websocket.sendKeyProduct("key_write_file", cmdData)
        }else{
          this.$message.warning('初始化成功，但写入KEY时发生错误')
          this.$msgbox.close()
        }
      })
    },
    // //请求MGXX授权点初始化
    // initEmpower(){
    //   keyEmpowerTally(this.initData.initJson,this.initData.macList).then(res => {
    //     if(res){
    //       //成功，获取mac地址、重写Key配置文件
    //       this.initData.macList = res.join(",")
    //       let cmdData = {
    //         "key_sn": this.keySn,
    //         "file_name": window.keyAuthorizedPointsFileName,
    //         "write_data": JSON.stringify(this.initData),
    //       }
    //       this.$websocket.sendKeyProduct("key_write_file", cmdData)
    //     }else{
    //       this.$message.warning('初始化成功，但写入KEY时发生错误')
    //       this.$msgbox.close()
    //     }
    //   })
    // },

    /**
     *  收到websocket消息处理
      */
    getSocketData(e) {

      const data = e && eval('(' + e.detail.data + ')');
      let resultData = data.result_data;
      //查询key序列号
      if (data.cmd_name === "key_scan") {
        this.keySn = resultData.key_sn
        if(!this.keySn){
          if(this.loginType=="1"){
            this.keyAccInit=true
          }else if((this.loginType=="0")){
            this.keyAccInit=true
          }
          this.errMsg = ''
          //客户标识
          this.sendProduct=''
          this.setIntervalKey=null
          this.lockKey=false
          this.initLockKey=false
          //key使用的账号
          this.keyAcc=''

          //key绑定的发货id
          this.keySendProduct=''
          this.keyTryTime=''
        }else{
          this.getKeyAcc()
          this.getKeyCustomer()
          if(this.keyEmpower==0){
            this.getKeyInit()
          }
          if(!this.initLockKey){
            this.getKey()
          }
        }
      }
      //验证pin
      if (data.cmd_name === "key_verify_pin") {
        if (0 !== data.err_code) {
          if(data.err_des.toString().trim()==='应用不存在'){
            this.lockKey = true
            this.errMsg ="操作失败，请重试"
          }
          //查询key是否被锁
          if(resultData.retry_count===0){
            if(!this.lockKey){
              //锁定KEY
              addlockKey(this.keySn).then(res => {
                this.lockKey = true
                this.loginForm.password = '';
                this.errMsg ="KEY已被锁定，请在"+res+"分钟后重试"
                this.lockKeyInterval()
              })
            }else{
              this.getKey()
            }
          }else{
            this.loginForm.password = '';
            this.errMsg = "密码不正确，剩余验证次数："+resultData.retry_count+"次"
            if (this.captchaOnOff) {
              this.getCode();
            }
          }

        }else{
         //执行登录操作
          this.errMsg = ''
          this.loginForm.pinLogin = true
          this.sendLogin();
        }
      }
      //查询文件
      if (data.cmd_name === "key_read_file") {
        if (0 === data.err_code) {
          //key使用人账户
          if(resultData.file_name===window.keyBasicFileName){
            let readData =  resultData.read_data && eval('(' + resultData.read_data + ')');
            this.keyAcc = readData.acc
            this.loginForm.username = readData.acc
            if(this.loginType=="1"){
              this.keyAccInit=false
            }else if((this.loginType=="0")){
              this.keyAccInit=false
            }
          }
          //试用期
          if(resultData.file_name===window.keyEmpowerFileName){
            this.tryTimeInit = false
            let readData =  resultData.read_data && eval('(' + resultData.read_data + ')');
            this.keySendProduct = readData.id
            this.keyTryTime = readData.try_time

          }
          //初始化授权点
          if(resultData.file_name===window.keyAuthorizedPointsFileName){
            let readData =  resultData.read_data && eval('(' + resultData.read_data + ')');
            this.initData = readData;
          }
        }
      }

      //写入文件反馈
      if (data.cmd_name === "key_write_file") {
        //初始化后重写AA01配置文件
        if (resultData.file_name === window.keyAuthorizedPointsFileName) {
          if (0 !== data.err_code || 0 === resultData.write_size) {
            this.submitLodding = false
            this.$message.error('初始化成功，但写入KEY时发生错误')
          } else {
            this.$message.success("初始化成功")
            this.$msgbox.close()
          }
        }
      }
    },
    //key验证pin
    keyVerifyPin(pwd) {
      if(!this.keySn){
        this.$message.warning("正在检测Key,请稍后重试")
        return ;
      }
      let cmdData = {"key_sn": this.keySn,"user_pin":pwd}
      this.$websocket.sendKeyProduct("key_verify_pin", cmdData)
    },
    getKey(){
      if(this.keySn){
        getLockKey(this.keySn).then(res => {
          this.lockKey = res.lockKey
          this.initLockKey = true
          if(res.lockKey){
            if(res.minute!==0){
              this.errMsg ="KEY已被锁定,请在"+res.minute+"分钟后重试"
            }else{
              //解锁操作
              this.errMsg = ''
              this.lockKey = false
              let cmdData = {"key_sn": this.keySn}
              this.$websocket.sendKeyProduct("key_unlock_pin", cmdData)
              if(this.setIntervalKey){
                clearInterval(this.setIntervalKey)
              }
            }
          }else{
            if(this.setIntervalKey){
              clearInterval(this.setIntervalKey)
            }
          }
        })
      }
    },
    //验证key绑定的账号试用期
    getKeyAcc(){
      if(this.keySn && this.keyAccInit){
        let cmdData = {"key_sn": this.keySn,file_name:window.keyBasicFileName}
        this.$websocket.sendKeyProduct("key_read_file", cmdData)
      }
    },
    //验证试用期
    getKeyCustomer(){
      if(this.keySn && this.tryTimeInit){
        let cmdData = {"key_sn": this.keySn,file_name:window.keyEmpowerFileName}
        this.$websocket.sendKeyProduct("key_read_file", cmdData)
      }
    },
    // //查询初始化授权配置文件
    getKeyInit(){
      if(this.keySn){
        let cmdData = {"key_sn": this.keySn,file_name:window.keyAuthorizedPointsFileName}
        this.$websocket.sendKeyProduct("key_read_file", cmdData)
      }
    },
    //开启定时任务查询锁key时间
    lockKeyInterval(){
      this.setIntervalKey = setInterval(() => {
        if(this.lockKey){
          this.getKey()
        }
      }, 30000)
    },
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.login {
  position: relative;
  height: 100%;
  background-image: url('../assets/images/background.png');
  background-size: cover;

  .logo {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 5%;
    left: 10%;

    img {
      width: 40px;
      height: 40px;
    }

    h3 {
      font-size: 24px;
      color: #fff;
      margin-left: 10px;
    }
  }
}

.login-form {
  position: absolute;
  top: 28.7%;
  right: 16.1%;
  border-radius: 15px;
  background: rgba($color: #232d6f, $alpha: 0.8);
  width: 410px;
  height: 420px;
  padding: 45px;

  svg {
    color: #7a92db;
  }

  .form-title {
    margin: 0 0 30px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 54px;
    width: 100%;

    img {
      width: 100%;
      margin-right: 10px;
    }
  }

  .form-text {
    color: white;
    vertical-align: middle;
    letter-spacing: 2px;

    .title {
      font-weight: 500;
      text-align: center;
      margin: 0;
      font-size: 30px;
    }

    p {
      padding: 0;
      margin: 0;
    }
  }

  .el-input {
    height: 40px;
    //width: 308px;
    color: white;

    input {
      height: 38px;
    }

    &::v-deep .el-input__inner {
      background: transparent;
      border: 1px solid rgba($color: #7a92db, $alpha: 0.6);
      color: white;
    }
  }

  .code_img {
    width: 15px;
    margin-top: 10px;
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;
  margin-right: 5px;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 20px;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

::v-deep .el-checkbox__label {
  color: #fff;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
